package com.hiwan.wechat.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hiwan.platform.utils.DateUtils;
import com.hiwan.system.util.DateUtil;
import com.hiwan.system.util.HttpUtil;
import com.hiwan.wechat.enumeration.CorpAppInfoEnum;
import com.hiwan.wechat.pojo.AccessToken;
import com.hiwan.wechat.pojo.NewsMessage;
import com.hiwan.wechat.pojo.NewsMessage.Article;
import com.hiwan.wechat.pojo.Ticket;
import com.hiwan.wechat.util.WechatRequestUrl;

import net.sf.json.JSONObject;

public class WechatService {
	public static Logger log = LoggerFactory.getLogger(WechatService.class);
	public static Map<String, AccessToken> accessTokenMap = new HashMap<String, AccessToken>();
	public static Map<String, Ticket> jsApiTicketMap = new HashMap<String, Ticket>();

	/**
	 * 获取AccessToken
	 * 
	 * @return
	 */
	public static AccessToken getAccessToken(String corpID, String secret) {
		AccessToken accessToken = null;

		String requestUrl = WechatRequestUrl.GET_ACCESS_TOKEN.replace("CorpID", corpID)
				.replace("SECRET", secret);
		JSONObject jsonObject = HttpUtil.httpRequest(requestUrl, "GET", null);
		// 如果请求成功
		if (null != jsonObject) {
			try {
				int errcode = jsonObject.getInt("errcode");
				if (errcode == 0){
					accessToken = new AccessToken();
					accessToken.setToken(jsonObject.getString("access_token"));
					accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
					accessToken.setDate(new Date());
				}else{
					return null;
				}
				log.info("获取token成功:" + jsonObject.getString("access_token") + "————" + jsonObject.getInt("expires_in"));
			} catch (Exception e) {
				e.printStackTrace();
				accessToken = null;
				// 获取token失败
				String error = String.format("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"),
						jsonObject.getString("errmsg"));
				log.debug(error);
			}
		}
		return accessToken;
	}

	/**
	 * 微信企业号 获取access_token    
	 * @Title: getAccessToken 
	 * @Description: 
	 * @param @return    
	 * @return AccessToken
	 */
	public static synchronized AccessToken getAccessToken(CorpAppInfoEnum key) {    
	    AccessToken accessToken = accessTokenMap.get(key.getAgentid());
	    if (accessToken == null || DateUtil.countDiffSeconds(new Date(), accessToken.getDate()) >= WechatRequestUrl.Timeout){
	    	accessToken = getAccessToken(WechatRequestUrl.CORP_ID, key.getSecret());
	    	accessTokenMap.put(key.getAgentid(), accessToken);
	    }
		return accessToken;
	}
	
	public static synchronized void updateAccessToken(CorpAppInfoEnum key, AccessToken accessToken) {    
		accessTokenMap.put(key.getAgentid(), accessToken);
	}
	
	/**
	 * 获取JsApiTicket
	 * 
	 * @param accessToken
	 * @return
	 */
	public static Ticket getJsApiTicket(String accessToken) {
		try {
			String requestUrl = WechatRequestUrl.JSAPI_TICKET_URL.replace("ACCESS_TOKEN", accessToken);
			JSONObject jsonObject = HttpUtil.httpRequest(requestUrl, "GET", null);
			int errcode = jsonObject.getInt("errcode");
			if (errcode == 0){
				Ticket ticket = new Ticket();
				ticket.setTicket(jsonObject.getString("ticket"));
				ticket.setExpiresIn(jsonObject.getInt("expires_in"));
				ticket.setDate(new Date());
				return ticket;
			}else{
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static synchronized Ticket getJsApiTicket(CorpAppInfoEnum key) {    
		Ticket jsApiTicket = jsApiTicketMap.get(key.getAgentid());
	    if (jsApiTicket == null || DateUtil.countDiffSeconds(new Date(), jsApiTicket.getDate()) >= WechatRequestUrl.Timeout){
	    	AccessToken accessToken = getAccessToken(key);
	    	jsApiTicket = getJsApiTicket(accessToken.getToken());
	    	jsApiTicketMap.put(key.getAgentid(), jsApiTicket);
	    }
		return jsApiTicket;
	}

	public static synchronized void updateJsApiTicket(CorpAppInfoEnum key) {
    	AccessToken accessToken = getAccessToken(key);
    	Ticket jsApiTicket = getJsApiTicket(accessToken.getToken());
		jsApiTicketMap.put(key.getAgentid(), jsApiTicket);
	}
	
	/**
	 * 通过授权获取的code，获取用户信息
	 * 
	 * @Title: getUserId
	 * @Description:
	 * @param @param
	 *            content
	 * @param @return
	 * @return JSONObject
	 */
	public static String getUserId(CorpAppInfoEnum corpApp, String code) {
		String accessToken  = WechatService.getAccessToken(corpApp).getToken();
		String requestUrl = WechatRequestUrl.GET_USER_INFO_URL.replace("ACCESS_TOKEN", accessToken).replace("CODE",
				code);
		JSONObject jsonObject = HttpUtil.httpRequest(requestUrl, "GET", "");
		// 如果请求成功
		if (null != jsonObject) {
			try {
				int errcode = jsonObject.getInt("errcode");
				if (errcode == 0){
					return jsonObject.getString("UserId");
				}else{
					String error = String.format("获取UserId失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"),
							jsonObject.getString("errmsg"));
					log.debug(error);
					if (WechatErrorCodeParse.isAccessTokenTimeOut(errcode)){
						getAccessToken(WechatRequestUrl.CORP_ID, corpApp.getSecret());
						getUserId(corpApp, code);
					}
					return null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	/**
	 * 获取企业用户信息
	 * @param accessToken
	 * @param code
	 * @return
	 */
	public static String getQyUserInfo(CorpAppInfoEnum corpApp, String userId) {
		String accessToken = WechatService.getAccessToken(corpApp).getToken();
		String requestUrl = WechatRequestUrl.GET_USER.replace("ACCESS_TOKEN", accessToken)
				.replace("USER_ID", userId);
		JSONObject jsonObject = HttpUtil.httpRequest(requestUrl, "GET", "");
		// 如果请求成功
		if (null != jsonObject) {
			try {
				int errcode = jsonObject.getInt("errcode");
				if (errcode == 0){
					return jsonObject.getString("avatar");
				}else{
					String error = String.format("获取QyUserInfo失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"),
							jsonObject.getString("errmsg"));
					log.debug(error);
					if (WechatErrorCodeParse.isAccessTokenTimeOut(errcode)){
						getAccessToken(WechatRequestUrl.CORP_ID, corpApp.getSecret());
						return getQyUserInfo(corpApp, userId);
					}
					return null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	/**
	 * 获取openid
	 * @param accessToken
	 * @param code
	 * @return
	 */
//	public static String getOpenId(String accessToken, String userId) {
//		String requestUrl = WechatRequestUrl.CONVERT_TO_OPENID.replace("ACCESS_TOKEN", accessToken);
//		JSONObject jsonobject = HttpUtil.httpRequest(requestUrl, "POST", userId);
//		return jsonobject.getString("openid");
//	}
	/**
	 * 获取头像信息
	 * @param accessToken
	 * @param openId
	 * @return
	 */
//	public static UserInfo getUserInfo(String accessToken,String openId){
//		UserInfo u=new UserInfo();
//		String requestUrl = WechatRequestUrl.GET_USERINFO.replace("ACCESS_TOKEN", accessToken)
//				.replace("OPENID", openId);
//		JSONObject jsonObject = HttpUtil.httpRequest(requestUrl, "GET", null);
//		u.setHeadimgurl(jsonObject.getString("headimgurl"));
//		return u;
//	}
	/**
	 * 群发接口
	 * 
	 * @param isToAll
	 *            true：群发所有人，tousers、topartys、totags传值null。
	 * @param tousers
	 *            用户userid列表,最多支持1000个,|分隔符
	 * @param topartys
	 *            用户所在部门列表,最多支持100个,|分隔符
	 * @param totags
	 *            用户所在标签列表，目前传null
	 * @param agentid
	 *            应用id
	 * @param articles,支持1到10条图文
	 * @return
	 */
	public static String publishNewsMsg(String accessToken, boolean isToAll, String tousers, String topartys,
			String totags, long agentid, List<Article> articles) {
		try {
			NewsMessage newsMessage = new NewsMessage();
			newsMessage.setAgentid(agentid);

			if (isToAll) {
				newsMessage.setTouser("@all");
			} else {
				if (tousers != null && !tousers.equals("")) {
					newsMessage.setTouser(tousers);
				}
				if (topartys != null && !topartys.equals("")) {
					newsMessage.setToparty(topartys);
				}
				if (totags != null && !totags.equals("")) {
					newsMessage.setTotag(totags);
				}
			}

			newsMessage.getNews().setArticles(articles);

			log.info("sendMessage >> " + newsMessage.parseToJsonStr());
			String requestUrl = WechatRequestUrl.SEND_MESSAGE_URL.replace("ACCESS_TOKEN", accessToken);
			JSONObject jsonobject = HttpUtil.httpRequest(requestUrl, "POST", newsMessage.parseToJsonStr());
			log.info(jsonobject.toString());
			return jsonobject.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	

	/**
	 * 用拿到的access_token采用http GET方式请求获取用户图片
	 * @return
	 */
	public static byte[] getTempMedia(String accessToken, String mediaId){
		try {
			String requestUrl = WechatRequestUrl.TEMP_MEDIA_GET_URL.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);
			byte[] imageInfo = HttpUtil.httpRequestimage(requestUrl, "GET", null);			
			return imageInfo;
		} catch (Exception e) { 
			e.printStackTrace();
		}
		return null; 
	
	}
	
	
	// public static WechatUserInfoVO getWechatOpenId(String code){
	// WechatUserInfoVO wechatUser=null;
	// String requestUrl = WechatRequestUrl.GET_OPENID.replace("APPID",
	// WechatRequestUrl.CORPID)
	// .replace("SECRET", WechatRequestUrl.SECRET).replace("CODE", code);
	// JSONObject jsonObject = HttpUtil.httpRequest(requestUrl, "GET", null);
	// log.info(jsonObject.toString());
	// // 如果请求成功
	// if (null != jsonObject) {
	// try {
	// wechatUser=new WechatUserInfoVO();
	// wechatUser.setAccessToken(jsonObject.getString("access_token"));
	// wechatUser.setExpiresIn(jsonObject.getInt("expires_in"));
	// wechatUser.setOpenid(jsonObject.getString("openid"));
	// wechatUser.setRefreshToken(jsonObject.getString("refresh_token"));
	// wechatUser.setScope(jsonObject.getString("scope"));
	// wechatUser=getWechatUserInfo(wechatUser);
	//// log.info("获取网页token,用户openid成功:"+jsonObject.getString("access_token")+"————"+jsonObject.getInt("expires_in")+"————"+jsonObject.getString("openid")+"————"+jsonObject.getString("refresh_token")+"————"+jsonObject.getString("scope"));
	// } catch (Exception e) {
	// e.printStackTrace();
	//// log.error("获取网页token,用户openid异常:"+jsonObject.getString("access_token")+"————"+jsonObject.getInt("expires_in")+"————"+jsonObject.getString("openid")+"————"+jsonObject.getString("refresh_token")+"————"+jsonObject.getString("scope"));
	// }
	// }
	// return wechatUser;
	// }
	// public static WechatUserInfoVO getWechatUserInfo(WechatUserInfoVO
	// wechatUser){
	// WechatUserInfoVO object=null;
	// String requestUrl = WechatRequestUrl.GET_USERINFO.replace("ACCESS_TOKEN",
	// wechatUser.getAccessToken())
	// .replace("OPENID", wechatUser.getOpenid());
	// JSONObject jsonObject = HttpUtil.httpRequest(requestUrl, "GET", null);
	// log.info(jsonObject.toString());
	// // 如果请求成功
	// if (null != jsonObject) {
	// try {
	// object=new WechatUserInfoVO();
	// object.setOpenid(jsonObject.getString("openid"));
	// object.setNickname(jsonObject.getString("nickname"));
	// object.setSex(jsonObject.getString("sex"));
	// object.setProvince(jsonObject.getString("province"));
	// object.setCity(jsonObject.getString("city"));
	// object.setCountry(jsonObject.getString("country"));
	// object.setHeadimgurl(jsonObject.getString("headimgurl"));
	// object.setPrivilege(jsonObject.getString("privilege"));
	//// log.info("获取网页token,用户openid成功:"+jsonObject.getString("access_token")+"————"+jsonObject.getInt("expires_in")+"————"+jsonObject.getString("openid")+"————"+jsonObject.getString("refresh_token")+"————"+jsonObject.getString("scope"));
	// } catch (Exception e) {
	// e.printStackTrace();
	//// log.error("获取网页token,用户openid异常:"+jsonObject.getString("access_token")+"————"+jsonObject.getInt("expires_in")+"————"+jsonObject.getString("openid")+"————"+jsonObject.getString("refresh_token")+"————"+jsonObject.getString("scope"));
	// }
	// }
	// return object;
	// }
}
